/**
 * @Title: ThumbnailUitl.java
 * @Copyright (C) 2017 龙图软件
 * @Description:
 * @Revision History:
 * @Revision 1.0 2017-11-23  yuanchunci
 */
 

package com.ycc.uitl;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.coobird.thumbnailator.Thumbnails;

import org.springframework.web.multipart.MultipartFile;

/**
 * @ClassName: ThumbnailUitl
 * @Description: Description of this class
 * @author <a href="mailto:XXX@qq.com">yuanchunci</a>于 2017-11-23 上午10:37:27
 */

public class ThumbnailUitl{
	 private static String DEFAULT_PREVFIX = "thumb_";
	 private static Boolean DEFAULT_FORCE = false;//建议该值为false
	 
	 
	 public static final int WIDTH = 100 ;
	 public static final int HEIGHT = 100 ;
	 /**
	  * <p>Title: thumbnailImage</p>
	  * <p>Description: 根据图片路径生成缩略图 </p>
	  * @param imagePath 原图片路径
	  * @param w   缩略图宽
	  * @param h   缩略图高
	  * @param prevfix 生成缩略图的前缀
	  * @param force  是否强制按照宽高生成缩略图(如果为false，则生成最佳比例缩略图)
	  */
	 public  byte[] thumbnailImage(String imagePath, int w, int h, String prevfix, boolean force){
		 byte[] temp=null;
		 File imgFile = new File(imagePath);
	  if(imgFile.exists()){
	   try {
	    // ImageIO 支持的图片类型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
	    String types = Arrays.toString(ImageIO.getReaderFormatNames());
	    String suffix = null;
	    // 获取图片后缀
	    if(imgFile.getName().indexOf(".") > -1) {
	     suffix = imgFile.getName().substring(imgFile.getName().lastIndexOf(".") + 1);
	    }// 类型和图片后缀全部小写，然后判断后缀是否合法
	    if(suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase()) < 0){
	    System.out.println("Sorry, the image suffix is illegal. the standard image suffix is {}." + types);
	    	return null ;
	    }
	    System.out.println("target image's size, width:{}, height:{}."+w+h);
	    Image img = ImageIO.read(imgFile);
	    if(!force){
	     // 根据原图与要求的缩略图比例，找到最合适的缩略图比例
	     int width = img.getWidth(null);
	     int height = img.getHeight(null);
	     if((width*1.0)/w < (height*1.0)/h){
	      if(width > w){
	       h = Integer.parseInt(new java.text.DecimalFormat("0").format(height * w/(width*1.0)));
	       System.out.println("change image's height, width:{}, height:{}."+w+h);
	      }
	     } else {
	      if(height > h){
	        w = Integer.parseInt(new java.text.DecimalFormat("0").format(width * h/(height*1.0)));
	        System.out.println("change image's width, width:{}, height:{}."+w+h);
	      }
	     }
	    }
	    BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
	    Graphics g = bi.getGraphics();
	    g.drawImage(img, 0, 0, w, h, Color.LIGHT_GRAY, null);
	    g.dispose();
	    String p = imgFile.getPath();
	    // 将图片保存在原目录并加上前缀
	    ImageIO.write(bi, suffix, new File(p.substring(0,p.lastIndexOf(File.separator)) + File.separator + prevfix +imgFile.getName()));
	    File file=new File(p.substring(0,p.lastIndexOf(File.separator)) + File.separator + prevfix +imgFile.getName());
	    FileInputStream fin = new FileInputStream(file);   
	    temp= new byte[fin.available()]; 
	    if(!file.exists()){    
            System.out.println("删除文件失败："+file.getName()+"文件不存在");    
            return null;    
        }else{    
            if(file.isFile()){ 
//            	fin.close();
//                file.delete(); 
//                System.gc();
            } 
        }    
	    System.out.println("缩略图在原路径下生成成功");
	   } catch (IOException e) {
		   System.out.println("generate thumbnail image failed."+e);
	   }
	  }else{
		  System.out.println("the image is not exist.");
	  }
	  return temp;
	 }
	 
	 /**
	 * @throws InterruptedException 
	 * @throws IOException 
	  * thumbnail生成缩略图
	  * @param file
	  * @param uploadPath
	  * @param realUploadPath
	  * @return
	  * @throws
	  */
	 public static byte[] thumbnail(HttpServletRequest request,MultipartFile file, String uploadPath, String realUploadPath,String uuid) throws IOException, InterruptedException {
		   String types = Arrays.toString(ImageIO.getReaderFormatNames());
		   String typesStr="mpg,mpeg,avi,rm,rmvb,mov,wmv,asf,dat(VCD),asx,wvx,mpe,mpa,mp4,mp3";

		   String suffix=null;
		   byte[] datas=null;
		   File fileFolder = new File(uploadPath);
		   if(!fileFolder .exists()){
			   fileFolder.mkdirs();  
			}
		   // 获取图片后缀
		   if(file.getOriginalFilename().indexOf(".") > -1) {
		      suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
		   }
		   if(suffix!=null&&types.toLowerCase().indexOf(suffix.toLowerCase()) < 0){
		       if(typesStr.toLowerCase().indexOf(suffix.toLowerCase())> 0){
		    	   System.out.println(System.getenv("Path"));
		    		  String cmd=null;
		    		  String[] str=System.getenv("Path").split(";");
		    		  for(int i=0;i<str.length;i++){
		    			  if(str[i].toLowerCase().indexOf("ffmpeg")>-1){
		    				  cmd=str[i]+"\\ffmpeg.exe";
		    				  break;
		    			  }
		    		  }
		    		  System.out.println(cmd);
		    		  if(cmd==null){
		    			  System.out.println("没有配置环境变量");
		    			  return null;
		    		  }
		    		  String cutPicPath=uploadPath+"/"+uuid+file.getOriginalFilename().substring(0, file.getOriginalFilename().indexOf(suffix))+"jpg";
//		    		  String imgPath=pic.cutPic(cmd, realUploadPath,cutPicPath);
		    		  String imgPath="";
		    		  if(FfmpegCutPic.cutPic(cmd, realUploadPath,cutPicPath)){
		    			  imgPath=cutPicPath;
		    		  }
		    		  datas=Convert.convertTostream(imgPath);
		       }
		   }
		   if(types.toLowerCase().indexOf(suffix.toLowerCase()) < 0&&typesStr.toLowerCase().indexOf(suffix.toLowerCase()) < 0){
			       System.out.println("Sorry, the image suffix is illegal. the standard image suffix is" + types);
			       String url=request.getSession().getServletContext().getRealPath("")+"\\images\\file.png";
				   System.out.println(url); 
				   datas= convertTostream(url);
		    }else if(suffix != null &&types.toLowerCase().indexOf(suffix.toLowerCase()) > 0){
		    	try {
			         String des = uploadPath +"/"+uuid+file.getOriginalFilename().substring(0, file.getOriginalFilename().indexOf(suffix))+"jpg";
//			         datas= file.getBytes();
			         Thumbnails.of(file.getInputStream()).size(WIDTH, HEIGHT).toFile(des);
			         File thumFile=new File(des);
			         FileInputStream fs=new FileInputStream(thumFile);
			         ByteArrayOutputStream bos = new ByteArrayOutputStream();
			         byte[] b = new byte[1024];
			         int n;
			         while ((n = fs.read(b)) != -1)
			            {
			                bos.write(b, 0, n);
			            }
			             fs.close();
			            bos.close();
			          datas=bos.toByteArray();
			        } catch(Exception e) {
			            e.printStackTrace() ;
			        } 
		    }
		 return datas;
	    }
	 
	 /**
		 * @throws IOException 
		  * thumbnail生成缩略图
		  * @param file
		  * @param uploadPath
		  * @param realUploadPath
		  * @return
		  * @throws
		  */
		 public static Map thumbnail(HttpServletRequest request,File file, String uploadPath, String realUploadPath,String uuid) throws IOException {
			   String types = Arrays.toString(ImageIO.getReaderFormatNames());
			   String typesStr="mpg,mpeg,avi,rm,rmvb,mov,wmv,asf,dat(VCD),asx,wvx,mpe,mpa,mp4,mp3";
               String fileName=file.getName();
			   String suffix=null;
			   Map result=new HashMap();
			   File fileThumFolder = new File(realUploadPath+"/thum");
			   if(!fileThumFolder .exists()){
				   fileThumFolder.mkdirs();  
				}
			   File fileFolder = new File(uploadPath);
			   if(!fileFolder .exists()){
				   fileFolder.mkdirs();  
				}
			   // 获取图片后缀
			   if(fileName.indexOf(".") > -1) {
			      suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
			   }
			   if(suffix!=null&&types.toLowerCase().indexOf(suffix.toLowerCase()) < 0){
			       if(typesStr.toLowerCase().indexOf(suffix.toLowerCase())> 0){
			    	   System.out.println(System.getenv("Path"));
			    		  String cmd=null;
			    		  String[] str=System.getenv("Path").split(";");
			    		  for(int i=0;i<str.length;i++){
			    			  if(str[i].toLowerCase().indexOf("ffmpeg")>-1){
			    				  cmd=str[i]+"\\ffmpeg.exe";
			    				  break;
			    			  }
			    		  }
			    		  System.out.println(cmd);
			    		  if(cmd==null){
			    			  System.out.println("没有配置环境变量");
			    			  return null;
			    		  }
			    		  String cutPicPath=realUploadPath+"/thum/"+fileName.substring(0, fileName.indexOf(suffix))+"jpg";
			    		  String to=copy(file.getPath(),uploadPath+"/"+uuid+fileName);
			    		  File f=new File(to);
			    		  FfmpegCutPic.cutPic(cmd, f.getPath(),cutPicPath);
			    		  
			       }
			   }
			   if(types.toLowerCase().indexOf(suffix.toLowerCase()) < 0&&typesStr.toLowerCase().indexOf(suffix.toLowerCase()) < 0){
				       System.out.println("Sorry, the image suffix is illegal. the standard image suffix is" + types);
				       String url=request.getSession().getServletContext().getRealPath("")+"\\images\\file.png";
//				       copy(file.getPath(),uploadPath+"/"+uuid + fileName);
				       result.put("url",url);
			    }else if(suffix != null &&types.toLowerCase().indexOf(suffix.toLowerCase()) > 0){
			    	try {
			    		  String des = realUploadPath +"/thum/"+fileName.substring(0, fileName.indexOf(suffix))+"jpg" ;
			    		 copy(file.getPath(),uploadPath+"/"+uuid + fileName);
				        Thumbnails.of(file).size(WIDTH, HEIGHT).toFile(des);
				        } catch(Exception e) {
				            e.printStackTrace() ;
				        } 
			    }
			   result.put("uploadPath", uploadPath);
			  return result;
		    }
		 
		 /**
			 * @throws IOException 
			  * thumbnail生成缩略图
			  * @param file
			  * @param uploadPath
			  * @param realUploadPath
			  * @return
			  * @throws
			  */
			 public static Map thumbnail(MultipartFile file, String uploadPath, String realUploadPath,String uuid) throws IOException {
				 String fileName =file.getOriginalFilename();// request.getParameter("filename"); // 2323928392489-美人鱼.avi
					Map result=new HashMap();
					 File fileFolder = new File(uploadPath);
					   if(!fileFolder .exists()){
						   fileFolder.mkdirs();  
					}  
				 InputStream in =file.getInputStream(); 
				   FileOutputStream fos=new FileOutputStream(realUploadPath+"//"+uuid+fileName);
				   BufferedOutputStream bos=new BufferedOutputStream(fos);
				   int b=-1;
//					byte[] bb=file.getBytes();
				   byte[] bufferin=new byte[1024];
				   while ((b = in.read(bufferin)) > 0) {
			            // 输出缓冲区的内容到浏览器，实现文件下载
					   bos.write(bufferin, 0, b);
			        }
				   bos.flush();
				   bos.close();
				   fos.close();
				   in.close();
			       result.put("filepath", realUploadPath+"/"+uuid+fileName);
					return result;
			    }
			 
			 
		 public  static String copy(String from,String to) throws IOException   
		    {
			 File fromFile=new File(from);
			 File toFile=new File(to);
			 FileInputStream fis=null;
			 FileOutputStream fos=null;
			 fis=new FileInputStream(fromFile);
			 fos=new FileOutputStream(toFile);
			 byte[]b=new byte[1024];
			 int len=0;
			 while((len=fis.read(b))!=-1){
				 fos.write(b, 0, len);
			 }
			 fis.close();
			 if(fos!=null){
				 fos.close();
			 }
				return to;   
		    }
	 /**
	  * 将文件转换成流
	  * @param url
	  * @return
	  * @throws IOException
	  * @throws
	  */
	 public static byte[] convertTostream(String url) throws IOException{
		  File thumbnailFile=new File(url);
          FileInputStream fis = new FileInputStream(thumbnailFile);  
	      System.out.println(fis);
	      byte[] b = new byte[1024];
	      ByteArrayOutputStream bos = new ByteArrayOutputStream(fis.available()); 
          int n;  
          while ((n = fis.read(b)) != -1) {  
              bos.write(b, 0, n);  
          }  
          fis.close();  
          bos.close();  
		return bos.toByteArray();
	 }
	 
}


